package com.example.aigc_education.integration.processor.v1;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.example.aigc_education.common.BusinessException;
import com.example.aigc_education.integration.config.RestTemplateUtils;
import com.example.aigc_education.integration.constants.CozeConstant;
import com.example.aigc_education.integration.impl.CozeTokenIntegrationImpI;
import com.example.aigc_education.integration.request.CozeRequest;
import com.example.aigc_education.integration.response.CozeResponse;
import com.example.aigc_education.utils.JsonUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

@Slf4j
public abstract class CozeSyncWFProcessor<T> {
    @Autowired
    private CozeTokenIntegrationImpI cozeTokenIntegration;

    private static final String COZE_SYNC_WORKFLOW_URL = "/workflow/run";

    protected abstract String workflowId();



    // 参数校验
    protected abstract boolean isParamValid(CozeRequest<T> request);


    private CozeResponse executeWorkFlow(CozeRequest<T> request) {
        if (!isParamValid(request)) {
            log.warn("CozeSyncWFProcessor executeWorkFlow error params:{}", JsonUtils.toJson(request));
            throw new BusinessException("参数校验失败");
        }

        // 设置工作流id 与 是否异步
        request.setWorkflowId(workflowId());
        request.setAsync(false);

        // 请求头设置
        Map<String, String> headerMap = new HashMap<>();
        String cozeToken = cozeTokenIntegration.getCozeToken();
        headerMap.put("Authorization",String.format("Bearer %s",cozeToken));
        headerMap.put("Content-Type", "application/json");

        // 转换为json对象
        JSONObject jsonObject = (JSONObject) JSON.toJSON(request);

//        String restResult = Optional.ofNullable(RestTemplateUtils.postHttp(CozeConstant.COZE_URL + COZE_SYNC_WORKFLOW_URL, jsonObject, headerMap))
//                .orElseThrow(() -> new BusinessException("请求coze失败"));
        String restResult = RestTemplateUtils.postHttp(CozeConstant.COZE_URL + COZE_SYNC_WORKFLOW_URL, jsonObject, headerMap);
        log.info("CozeSyncWFProcessor executeWorkFlow response:{}", restResult);


        // 将返回结果转换为CozeSyncResponse对象
        return JsonUtils.fromJson(restResult, CozeResponse.class);
    }

    public <R> R runWorkFlow(CozeRequest<T> request, Class<R> responseType) {
        CozeResponse cozeResponse = executeWorkFlow(request);

        String data = Optional.ofNullable(cozeResponse)
                .map(CozeResponse::getData)
                .orElse(null);

        R response = Optional.ofNullable(data)
                .map(d -> JsonUtils.fromJson(d, responseType))
                .orElse(null);
        log.info("CozeSyncWFProcessor runWorkFlow response:{}", JsonUtils.toJson(response));

        return response;
    }


}
